<template>
    <el-upload ref="upload" v-model:file-list="fileList" multiple class="upload-demo" action="#" :show-file-list="false"
        :http-request="submitUpload" :before-upload="beforeUpload" :on-remove="Remove" :on-change="handleChange">
        <el-button type="primary">批量上传</el-button>
    </el-upload>
    <div class="ts-form-table">
        <el-table :data="dataList" ref="table" :key="toggleIndex" width="400" border stripe
            :header-cell-style="{ 'color': '#000' }">
            <el-table-column v-if="edit" label="" width="58">
                <template #default="scope">
                    <el-tag @click="rowEdit(scope.row)">
                        <Edit style="width: 1em; height: 1em;" />
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column type="index" width="50" fixed="left">
                <template #default="scope">
                    <div class="ts-form-table-handle">
                        <span>{{ scope.$index + 1 }}</span>
                        <el-button type="danger" size="small" :icon="Delete" plain circle
                            @click="rowDel(scope.row, scope.$index)">
                        </el-button>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="" width="58">
                <template #default>
                    <el-tag class="move" style="cursor: move;">
                        <DCaret style="width: 1em; height: 1em;" />
                    </el-tag>
                </template>
            </el-table-column>
            <slot v-if="dataList.length > 0" name="tableContent"></slot>
            <template #empty>
                {{ placeholder }}
            </template>
        </el-table>
    </div>
</template>
<script setup>
import { ref, reactive, watch, onMounted, nextTick,defineModel } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { Plus, Delete, DCaret, Edit } from '@element-plus/icons-vue';
import Sortable from 'sortablejs'
const emit = defineEmits(['add', 'updateIndex','delete'])
const props = defineProps({
    modelValue: { type: Array, default: () => [] },
    addTemplate: { type: Object, default: () => { } },
    placeholder: { type: String, default: "暂无数据" },
    apiObj: { type: Object, default: () => { } },
    edit: { type: Boolean, default: false }
})
const fileList = ref([])
const dataList = defineModel()
const upload = ref(null)
const table = ref(null)
const toggleIndex = ref(0)
const repeatUpload = ref(false)
const submitFile = ref(false)
// const flag = watch(() => props.modelValue, (newValue,oldValue) => {
//     if(submitFile.value == false){
//         dataList.value = JSON.parse(JSON.stringify(newValue))
//     }
//     if (newValue) {
//         flag()
//     }
// }, {
//     deep: true
// })
onMounted(() => {
    rowDrop()
})
const handleChange = (file, fileList) => {
    // 检查是否有重复文件，有的话删除新选择的文件     
    if (fileList.findIndex(f => f.name === file.name) != fileList.findLastIndex(f => f.name === file.name) ||dataList.value.findIndex(f => f.fileName === file.name)!==-1) {
        ElMessage.info(file.name + " 文件已存在")
        fileList.pop()
        repeatUpload.value = true
    }
    else {
        repeatUpload.value = false
    }
}
const submitUpload = (data) => {
    submitFile.value = true
    if (repeatUpload.value == false) {
        const temp = JSON.parse(JSON.stringify(props.addTemplate))
        temp.operationType = 'add'
        temp.fileFullPath = URL.createObjectURL(data.file)
        temp.file = data.file
        temp.itemIndex = dataList.value.length + 1
        temp.fileName = data.file.name
        dataList.value.push(temp)
        emit('add')
    }
}
const rowDel = (row, index) => {
    if (row.operationType!=='add' && props.apiObj) {
        ElMessageBox.confirm('确定删除这条记录吗', '提示', {
            type: 'warning',
            confirmButtonText: '确定',
            confirmButtonClass: 'el-button--danger'
        }).then(() => {
            deleteFile(row, index)
        }).catch(() => { })
    }
    else {
        dataList.value.splice(index, 1)
        if(row.id ==''||row.id ==null||row.id==undefined){
            upload.value.handleRemove(row.file)
        }
        emit('updateIndex')
        if(row.operationType!=='add'){
            row.operationType = 'delete'
            emit('delete',row)
        }
    }
}
const rowDrop = () => {
    const tbody = table.value.$el.querySelector('.el-table__body-wrapper tbody')
    Sortable.create(tbody, {
        handle: ".move",
        animation: 300,
        ghostClass: "ghost",
        onEnd({ newIndex, oldIndex }) {
            const tableData = dataList.value
            const currRow = tableData.splice(oldIndex, 1)[0]
            tableData.splice(newIndex, 0, currRow)
            emit('updateIndex')
            toggleIndex.value += 1
            nextTick(() => {
                rowDrop()
            })
        }
    })
}
const rowEdit = (item) => {
    if (item.operationType == '') {
        item.operationType = 'update'
    }
    // else if (item.operationType == 'update') {
    //     item.operationType = ''
    // }
}
const deleteFile = async (row, index) => {
    let params = {
        id: row.id
    }
    let res = await props.apiObj.post(params)
    if (res.code == 200) {
        dataList.value.splice(index, 1)
        // upload.value.handleRemove(row.file)
        emit('updateIndex')
        ElNotification.success({ message: '删除成功！', duration: 2000 });
    }
}
</script>
<style scoped>
.ts-form-table {
    width: 100%;
    margin-top: 10px;
}

.ts-form-table .ts-form-table-handle {
    text-align: center;
}

.ts-form-table .ts-form-table-handle span {
    display: inline-block;
}

.ts-form-table .ts-form-table-handle button {
    display: none;
}

.ts-form-table .hover-row .ts-form-table-handle span {
    display: none;
}

.ts-form-table .hover-row .ts-form-table-handle button {
    display: inline-block;
}
</style>